<?php

namespace App\Common\Tools;

use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;

class Captcha
{

    protected $builder;
    protected $pharse;
    protected $code;
    protected $captchaId;

    /**
     * Undocumented function
     *
     * @return
     */
    public function __construct(CaptchaBuilder $builder)
    {
        $this->pharse  = new PhraseBuilder();
        $this->code    = $this->pharse->build($len);
        $this->builder = $builder;
        $this->builder->setMaxBehindLines(0);
        $this->builder->setMaxFrontLines(0);
    }

    /**
     * Undocumented function
     *
     * @return
     */
    public function inline()
    {
        $phrase = $this->builder->getPhrase();
        $key = Str::ulid()->toBase32();
        $cacheKey = $this->getCacheKey($key);
        Cache::set($cacheKey, $phrase, 900); // 15 min
        return [
            'secret_str'  => $key,
            'src'         => $this->builder->build()->inline(),
            'verify_type' => 'picture',
        ];
    }

    /**
     * 获取验证码的缓存key
     *
     * @return string
     */
    public function getCacheKey($key):string
    {
        return sprintf('captcha:%s', $key);
    }

    public function getPhrase()
    {
        return $this->builder->getPhrase();
    }

    /**
     * 以base64的形式输出验证码
     * @return string
     */
    public function inline2()
    {
        return $this->builder->inline();
    }

    /**
     * 生成客户端id
     * @return string
     */
    public function buildCaptchaId(): void
    {
        $this->captchaId = md5(mt_rand(1000, 9999). microtime(true));
    }

    /**
     * 获取验证码id
     * @return string
     */
    public function getCaptchaId(): string
    {
        if (!$this->captchaId) {
            $this->buildCaptchaId();
        }
        return $this->captchaId;
    }

    /**
     * 输出图片
     */
    public function output()
    {
        $this->builder->output();
    }

    /**
     * 设置背景色
     * @param int $red
     * @param int $green
     * @param int $blue
     * @return $this
     */
    public function setBackgroundColor($red = 220, $green = 210, $blue = 230)
    {
        $this->builder->setBackgroundColor($red, $green, $blue);
        return $this;
    }

    /**
     * 设置最大角度
     * @param int $angle
     * @return $this
     */
    public function setMaxAngle($angle = 20): self
    {
        $this->builder->setMaxAngle($angle);
        return $this;
    }

    /**
     * 设置宽高
     * @param int $width
     * @param int $height
     * @return $this
     */
    public function setWidthHeight($width = 120, $height = 40): self
    {
        $this->builder->build($width, $height);
        return $this;
    }
}